/* Copyright Statement:
 *
 * This software/firmware and related documentation ("AutoChips Software") are
 * protected under relevant copyright laws. The information contained herein is
 * confidential and proprietary to AutoChips Inc. and/or its licensors. Without
 * the prior written permission of AutoChips inc. and/or its licensors, any
 * reproduction, modification, use or disclosure of AutoChips Software, and
 * information contained herein, in whole or in part, shall be strictly
 * prohibited.
 *
 * AutoChips Inc. (C) 2023. All rights reserved.
 *
 * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
 * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("AUTOCHIPS SOFTWARE")
 * RECEIVED FROM AUTOCHIPS AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
 * ON AN "AS-IS" BASIS ONLY. AUTOCHIPS EXPRESSLY DISCLAIMS ANY AND ALL
 * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NONINFRINGEMENT. NEITHER DOES AUTOCHIPS PROVIDE ANY WARRANTY WHATSOEVER WITH
 * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
 * INCORPORATED IN, OR SUPPLIED WITH THE AUTOCHIPS SOFTWARE, AND RECEIVER AGREES
 * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
 * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
 * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN AUTOCHIPS
 * SOFTWARE. AUTOCHIPS SHALL ALSO NOT BE RESPONSIBLE FOR ANY AUTOCHIPS SOFTWARE
 * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
 * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AUTOCHIPS'S
 * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE AUTOCHIPS SOFTWARE
 * RELEASED HEREUNDER WILL BE, AT AUTOCHIPS'S OPTION, TO REVISE OR REPLACE THE
 * AUTOCHIPS SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
 * CHARGE PAID BY RECEIVER TO AUTOCHIPS FOR SUCH AUTOCHIPS SOFTWARE AT ISSUE.
 */

/*!
 * @file ac780x_eflash.c
 *
 * @brief This file provides EFLASH integration functions.
 *
 */

/* ===========================================  Includes  =========================================== */
#include "ac780x_eflash_reg.h"

/* ============================================  Define  ============================================ */
#define EFLASH_UNLOCK_KEY1               (0xac7803UL)     /* eflash controler ulock key 1    */
#define EFLASH_UNLOCK_KEY2               (0x01234567UL)   /* eflash controler ulock key 2    */
#define PFLASH_WRITE_PROTECT_NUM         (4UL)            /* P-flash write protection option byte address total count */
#define PFLASH_READ_PROTECT_NUM          (1UL)            /* Read protection option byte address total count */
#define DFLASH_WRITE_PROTECT_NUM         (4UL)            /* D-Flash write protection option byte address total count */
#define EXTERN_RESET_CTRL_NUM            (1UL)            /* External reset control info address total count */

/* ==========================================  Variables  =========================================== */
/*!
 * @brief Flash callback pointer.
 */
static DeviceCallback_Type s_eccFlashCallback = NULL;

/* ======================================  Functions define  ======================================== */
/*!
 * @brief Unlock the eflash controller.
 *
 * @param[in] none
 * @return EFLASH STATUS: eflash operation status
 */
EFLASH_StatusType EFLASH_UnlockCtrl(void)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;
    uint8_t ctrlLockBit = 0U;
    uint32_t timeoutCount = 0U;

    ctrlLockBit = EFLASH_GetCtrlLockBitReg();
    while (1U == ctrlLockBit)
    {
        EFLASH_SetKeyReg(EFLASH_UNLOCK_KEY1);
        EFLASH_SetKeyReg(EFLASH_UNLOCK_KEY2);

        if (100U < timeoutCount)
        {
            statusRes = EFLASH_STATUS_TIMEOUT;
            break;
        }
        ctrlLockBit = EFLASH_GetCtrlLockBitReg();
        timeoutCount++;
    }

    return statusRes;
}

/*!
 * @brief Lock the eflash controler.
 *
 * @param[in] none
 * @return none
 */
void EFLASH_LockCtrl(void)
{
    EFLASH_LockCtrlReg();
}

/*!
 * @brief Read a specified length of data from the eflash specified address.
 *
 * @param[in] addr: eflash address
 * @param[in] buffer: Point to the data bufffer for saving the read data
 * @param[in] len: read length(the unit is word)
 * @return none
 */
void EFLASH_Read(uint32_t addr, uint32_t *buffer, uint32_t len)
{
    uint32_t i;

    DEVICE_ASSERT(((PFLASH_BASE_ADDRESS <= addr) && (DFLASH_END_ADDRESS > addr)) \
                  || ((DINFO_BASE <= addr) && (DINFO_END > addr)));
    DEVICE_ASSERT(NULL != buffer);

    for (i = 0U; i < len; i++)
    {
        buffer[i] = *(uint32_t*)addr;
        addr += 4U;
    }
}

/*!
 * @brief Perform start command sequence on eflash.
 *
 * @param[in] none
 * @return operation status
 *        - EFLASH_STATUS_SUCCESS: Operation was successful
 *        - EFLASH_STATUS_ERROR:   Operation was failure
 */
static EFLASH_StatusType FLASH_StartCmdSequence(void)
{
    EFLASH_StatusType  ret = EFLASH_STATUS_SUCCESS;

    /* trigger command execute */
    EFLASH_TrigCtrlCmdReg();
    /* Wait till busy bit is cleared */
    while (EFLASH_GetCmdBusyStatus());

    /* Check command execute error status */
    if (EFLASH_GetStatusReg())
    {
        ret = EFLASH_STATUS_ERROR;
    }

    return ret;
}

/*!
 * @brief Erase specified eflash user area address.
 *
 * @param[in] addr: eflash page addrees to be erased (should be 4-aligned)
 * @return EFLASH STATUS: eflash operation status
 */
EFLASH_StatusType EFLASH_PageErase(uint32_t addr)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;

    /* check eflash address */
    DEVICE_ASSERT(((PFLASH_BASE_ADDRESS <= addr) && (DFLASH_END_ADDRESS > addr)) \
                  || ((OPTION_END <= addr) && (CINFO_END > addr)) \
                  || ((DINFO_BASE <= addr) && (DINFO_END > addr)));

    /* Wait for last operation to be completed */
    if (EFLASH_GetCmdBusyStatus())
    {
        statusRes = EFLASH_STATUS_BUSY;
    }
    else
    {
        EFLASH_CLEAR_STAT_ERROR_BITS();
        /* Configure start address */
        EFLASH_SetStartAddressReg(addr);

        /* Configure command */
        EFLASH_SetCommandReg((uint32_t)EFLASH_CMD_PAGERASE);

        /* Trigger to start */
        statusRes = FLASH_StartCmdSequence();
    }

    return statusRes;
}

/*!
 * @brief Mass erase P-Flash or D-Flash.
 *
 * @param[in] addr: Specified eflash addrees to mass erase
 *            - P-Flash address: Mass erase P-Flash
 *            - D-Flash address: Mass erase D-Flash
 * @return EFLASH STATUS: eflash operation status
 */
EFLASH_StatusType EFLASH_MassErase(uint32_t addr)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;

    /* check eflash address */
    DEVICE_ASSERT((PFLASH_BASE_ADDRESS <= addr) && (DFLASH_END_ADDRESS > addr));

    /* Wait for last operation to be completed */
    if (EFLASH_GetCmdBusyStatus())
    {
        statusRes = EFLASH_STATUS_BUSY;
    }
    else
    {
        EFLASH_CLEAR_STAT_ERROR_BITS();
        /* Configure start address */
        EFLASH_SetStartAddressReg(addr);

        /* Configure command */
        EFLASH_SetCommandReg((uint32_t)EFLASH_CMD_MASSRASE);

        /* Trigger to start */
        statusRes = FLASH_StartCmdSequence();
    }

    return statusRes;
}

/*!
 * @brief User page program unit.
 *
 * @param[in] addr: eflash addrees to be programed (should be 4-aligned)
 * @param[in] buffer: Point to the data to be programed
 * @param[in] len: Data length to be programed (the unit is word)
 * @param[in] cntBase: the base value from which the length start to increase
 * @return EFLASH STATUS: eflash operation status
 */
static EFLASH_StatusType EFLASH_PageProgramUnit(uint32_t addr, uint32_t *buffer, uint32_t len, uint32_t cntBase)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;
    uint32_t dataCount = 0x0U;

    /* Wait for last operation to be completed */
    if (EFLASH_GetCmdBusyStatus())
    {
        statusRes = EFLASH_STATUS_BUSY;
    }
    else
    {
        EFLASH_CLEAR_STAT_ERROR_BITS();
        /* Configure start address */
        EFLASH_SetStartAddressReg(addr);
        /* Configure length (unit is 32-bit)*/
        EFLASH_SetLengthReg(len);
        /* Configure command */
        EFLASH_SetCommandReg((uint32_t)EFLASH_CMD_PAGEPROGRAM);

        /* Trigger to start */
        EFLASH_TrigCtrlCmdReg();

        /* Check error */
        if (!(EFLASH_GetStatusReg() & EFLASH_CSR_PGMERR_Msk))
        {
            /*program data */
            for (dataCount = cntBase; dataCount < (cntBase + len); )
            {
                if (EFLASH_GetDataBufferReg())
                {
                    EFLASH_SetDataReg(buffer[dataCount]);
                    dataCount++;
                }
            }
            /* Check whether the command is finished */
            while (EFLASH_GetCmdBusyStatus());
            if (EFLASH_GetStatusReg())
            {
                statusRes = EFLASH_STATUS_ERROR;
            }
        }
        else
        {
            statusRes = EFLASH_STATUS_ERROR;
        }
    }

    return statusRes;
}

/*!
 * @brief User page program.
 *
 * @param[in] addr: eflash addrees to be programed (should be 4-aligned)
 * @param[in] buffer: Point to the data to be programed
 * @param[in] len: Data length to be programed (the unit is word)
 * @return EFLASH STATUS: eflash operation status
 */
EFLASH_StatusType EFLASH_PageProgram(uint32_t addr, uint32_t *buffer, uint32_t len)
{
    uint32_t dataLength1 = 0U;
    uint32_t dataLength2 = 0U;
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;

    /* check eflash address */
    DEVICE_ASSERT(((PFLASH_BASE_ADDRESS <= addr) && (DFLASH_END_ADDRESS > addr)) \
                  || ((OPTION_END <= addr) && (CINFO_END > addr)) \
                  || ((DINFO_BASE <= addr) && (DINFO_END > addr)));
    DEVICE_ASSERT(len != 0U);
    DEVICE_ASSERT(NULL != buffer);

    if((addr >= PFLASH_BASE_ADDRESS) && (addr < PFLASH_END_ADDRESS) && ((addr + len * 4U) > DFLASH_BASE_ADDRESS))
    {
        dataLength2 = (addr + len * 4U - DFLASH_BASE_ADDRESS) / 4U;
        dataLength1 = (DFLASH_BASE_ADDRESS - addr) / 4U;
        statusRes = EFLASH_PageProgramUnit(addr, buffer, dataLength1, 0U);
        if (EFLASH_STATUS_SUCCESS == statusRes)
        {
            statusRes = EFLASH_PageProgramUnit(DFLASH_BASE_ADDRESS, buffer, dataLength2, dataLength1);
        }
    }
    else
    {
        statusRes = EFLASH_PageProgramUnit(addr, buffer, len, 0U);
    }

    return statusRes;
}

/*!
 * @brief Verify whether the page erase operation is performed successfully(unit function).
 *
 * @param[in] addr: eflash addrees to be verified (should be 4-aligned)
 * @param[in] len: page erase verify length(the unit is word)
 * @return EFLASH STATUS: eflash operation status
 */
static EFLASH_StatusType EFLASH_PageEraseVerifyUnit(uint32_t addr, uint32_t len)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;

    /* Wait for last operation to be completed */
    if (EFLASH_GetCmdBusyStatus())
    {
        statusRes = EFLASH_STATUS_BUSY;
    }
    else
    {
        EFLASH_CLEAR_STAT_ERROR_BITS();
        /* Configure start address */
        EFLASH_SetStartAddressReg(addr);

        /* Configure command and CMD_ST goes back to 0 */
        EFLASH_SetCommandReg((uint32_t)EFLASH_CMD_PAGERASEVERIFY);
        /* Configure length (unit is 32-bit)*/
        EFLASH_SetLengthReg(len);

        /* Trigger to start */
        statusRes = FLASH_StartCmdSequence();
    }

    return statusRes;
}

/*!
 * @brief Verify whether the page erase operation is performed successfully.
 *
 * @param[in] addr: eflash addrees to be verified (should be 4-aligned)
 * @param[in] len: page erase verify length(the unit is word)
 * @return EFLASH STATUS: eflash operation status
 */
EFLASH_StatusType EFLASH_PageEraseVerify(uint32_t addr, uint32_t len)
{
    uint32_t dataLength1 = 0U;
    uint32_t dataLength2 = 0U;
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;

    /* check eflash address */
    DEVICE_ASSERT(((PFLASH_BASE_ADDRESS <= addr) && (DFLASH_END_ADDRESS > addr)) \
                  || ((OPTION_END <= addr) && (CINFO_END > addr)) \
                  || ((DINFO_BASE <= addr) && (DINFO_END > addr)));
    DEVICE_ASSERT(len != 0U);

    if((addr >= PFLASH_BASE_ADDRESS) && (addr < PFLASH_END_ADDRESS) && ((addr + len * 4U) > DFLASH_BASE_ADDRESS))
    {
        dataLength2 = (addr + len * 4U - DFLASH_BASE_ADDRESS) / 4U;
        dataLength1 = (DFLASH_BASE_ADDRESS - addr) / 4U;
        statusRes = EFLASH_PageEraseVerifyUnit(addr,  dataLength1);
        if (EFLASH_STATUS_SUCCESS == statusRes)
        {
            statusRes = EFLASH_PageEraseVerifyUnit(DFLASH_BASE_ADDRESS, dataLength2);
        }
    }
    else
    {
        statusRes = EFLASH_PageEraseVerifyUnit(addr, len);
    }

    return statusRes;
}

/*!
 * @brief Verify whether the mass erase operation is performed successfully.
 *
 * @param[in] addr: Specified eflash addrees to mass erase verify
 *            - P-Flash address: Mass erase verify P-Flash
 *            - D-Flash address: Mass erase verify D-Flash
 * @return EFLASH STATUS: eflash operation status
 */
EFLASH_StatusType EFLASH_MassEraseVerify(uint32_t addr)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;

    /* check eflash address */
    DEVICE_ASSERT((PFLASH_BASE_ADDRESS <= addr) && (DFLASH_END_ADDRESS > addr));

    /* Wait for last operation to be completed */
    if (EFLASH_GetCmdBusyStatus())
    {
        statusRes = EFLASH_STATUS_BUSY;
    }
    else
    {
        EFLASH_CLEAR_STAT_ERROR_BITS();

        /* Configure start address */
        EFLASH_SetStartAddressReg(addr);

        /* Configure command and CMD_ST goes back to 0 */
        EFLASH_SetCommandReg((uint32_t)EFLASH_CMD_MASSRASEVERIFY);

        /* Trigger to start */
        statusRes = FLASH_StartCmdSequence();
    }

    return statusRes;
}

/*!
 * @brief Option page erase.
 *
 * @param[in] addr: option addrees to erase (should be 4-aligned)
 * @return EFLASH STATUS: eflash operation status
 */
static EFLASH_StatusType EFLASH_OptionPageErase(uint32_t addr)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;

    /* check option byte address */
    DEVICE_ASSERT(OPTION_BASE <= addr);
    DEVICE_ASSERT(OPTION_END > addr);

    /* Wait for last operation to be completed */
    if (EFLASH_GetCmdBusyStatus())
    {
        statusRes = EFLASH_STATUS_BUSY;
    }
    else
    {
        EFLASH_CLEAR_STAT_ERROR_BITS();
        /* Configure start address */
        EFLASH_SetStartAddressReg(addr);
        /* Configure command */
        EFLASH_SetCommandReg((uint32_t)EFLASH_CMD_PROTECTERASE);
        /* enable option byte area operation */
        EFLASH_EnableOptionReg(ENABLE);
        /* Trigger to start */
        statusRes = FLASH_StartCmdSequence();
    }
    /* disable option byte area operation */
    EFLASH_EnableOptionReg(DISABLE);

    return statusRes;
}

/*!
 * @brief Programs data to specified option page address.
 *
 * @param[in] addr: option addrees (should be 4-aligned)
 * @param[in] buffer: Point to the data bufffer to be programed
 * @param[in] len: Data length to be programmed (the unit is word)
 * @return EFLASH STATUS: eflash operation status
 */
static EFLASH_StatusType EFLASH_OptionPageProgram(uint32_t addr, uint32_t *buffer, uint32_t len)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;
    uint32_t dataCount = 0x0UL;

    /* check option byte address */
    DEVICE_ASSERT(OPTION_BASE <= addr);
    DEVICE_ASSERT(OPTION_END > addr);
    DEVICE_ASSERT(NULL != buffer);

    /* Wait for last operation to be completed */
    if (EFLASH_GetCmdBusyStatus())
    {
        statusRes = EFLASH_STATUS_BUSY;
    }
    else
    {
        EFLASH_CLEAR_STAT_ERROR_BITS();
        /* Configure start address */
        EFLASH_SetStartAddressReg(addr);
        /* Configure length (unit is 32-bit) */
        EFLASH_SetLengthReg(len);
        /* Configure command */
        EFLASH_SetCommandReg((uint32_t)EFLASH_CMD_PROTECTROGRAM);
        /* enable option byte area operation */
        EFLASH_EnableOptionReg(ENABLE);
        /* Trigger to start */
        EFLASH_TrigCtrlCmdReg();

        /* user program data */
        for (dataCount = 0UL; dataCount < len;)
        {
            if (EFLASH_GetDataBufferReg())
            {
                EFLASH_SetDataReg(buffer[dataCount]);
                dataCount++;
            }
        }

        /* Check whether the command is finished */
        while (EFLASH_GetCmdBusyStatus());
        if (EFLASH_GetStatusReg())
        {
            statusRes = EFLASH_STATUS_ERROR;
        }
    }
    /* disable option byte area operation */
    EFLASH_EnableOptionReg(DISABLE);

    return statusRes;
}

/*!
 * @brief Enable EFLASH read protection.
 *
 * This API is used to set(enable) EFLASH read protection. Set(enable) read
 * protection will take effect after reset and the all EFLASH main memory(user
 * pages) will return with 0xAAAAAAAA when read by JTAG/SWD. EFLASH main memory
 * can not be erased or programed by code/JTAG/SWD when in read protection status.
 *
 * @param[in] none
 * @return EFLASH STATUS: eflash operation status
 */
EFLASH_StatusType EFLASH_EnableReadProtection(void)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;
    uint32_t optBuffer[PFLASH_READ_PROTECT_NUM] = {0U};

    EFLASH_CLEAR_STAT_ERROR_BITS();
    statusRes = EFLASH_OptionPageErase(CINFO_BASE);
    if (EFLASH_STATUS_SUCCESS != statusRes)
    {
        statusRes = EFLASH_STATUS_ERROR;
    }
    else
    {
        optBuffer[0] = 0x5AA55AA5UL;
        statusRes = EFLASH_OptionPageProgram(CINFO_BASE, optBuffer, PFLASH_READ_PROTECT_NUM);
    }

    return statusRes;
}

/*!
 * @brief Disable EFLASH read protection.
 *
 * This API is used to clear(disable) EFLASH read protection. Clear(disable) read
 * protection will take effect after reset and the EFLASH main memory(user pages)
 * will be erased to 0xFFFFFFFF automatically.
 *
 * @param[in] none
 * @return EFLASH STATUS: eflash operation status
 */
EFLASH_StatusType EFLASH_DisableReadProtection(void)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;
    uint32_t optBuffer[PFLASH_READ_PROTECT_NUM] = {0UL};

    EFLASH_CLEAR_STAT_ERROR_BITS();
    statusRes = EFLASH_OptionPageErase(CINFO_BASE);
    if (EFLASH_STATUS_SUCCESS != statusRes)
    {
        statusRes = EFLASH_STATUS_ERROR;
    }
    else
    {
        optBuffer[0] = 0xFFFFFFACUL;
        statusRes = EFLASH_OptionPageProgram(CINFO_BASE, optBuffer, PFLASH_READ_PROTECT_NUM);
    }

    return statusRes;
}

/*!
 * @brief Set P-Flash write protection by option byte.
 *
 * @param[in] protectStatus: write protection status value
 * @return EFLASH STATUS: eflash operation status
 */
EFLASH_StatusType EFLASH_PFSetWriteProtection(uint32_t *protectStatus)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;
    uint32_t optBuffer[PFLASH_WRITE_PROTECT_NUM] = {0U};

    DEVICE_ASSERT(NULL != protectStatus);

    EFLASH_CLEAR_STAT_ERROR_BITS();
    statusRes = EFLASH_OptionPageErase(PFLASH_WRITE_PROTECT_BASE);
    if (EFLASH_STATUS_SUCCESS == statusRes)
    {
        optBuffer[0] = protectStatus[0] & 0xFFFFUL;
        optBuffer[1] = (protectStatus[0] >> 16U) & 0xFFFFU;
        optBuffer[2] = protectStatus[1] & 0xFFFFU;
        optBuffer[3] = (protectStatus[1] >> 16U) & 0xFFFFU;
        statusRes = EFLASH_OptionPageProgram(PFLASH_WRITE_PROTECT_BASE, optBuffer, PFLASH_WRITE_PROTECT_NUM);
        if (EFLASH_STATUS_SUCCESS != statusRes)
        {
            statusRes = EFLASH_STATUS_ERROR;
        }
    }
    else
    {
        statusRes = EFLASH_STATUS_ERROR;
    }

    return statusRes;
}

/*!
 * @brief Set D-Flash write protection by option byte.
 *
 * @param[in] protectStatus: write protection status value
 * @return EFLASH STATUS: eflash operation status
 */
EFLASH_StatusType EFLASH_DFSetWriteProtection(uint32_t *protectStatus)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;
    uint32_t optBuffer[DFLASH_WRITE_PROTECT_NUM] = {0U};

    EFLASH_CLEAR_STAT_ERROR_BITS();
    statusRes = EFLASH_OptionPageErase(DFLASH_WRITE_PROTECT_BASE);
    if (EFLASH_STATUS_SUCCESS == statusRes)
    {
        optBuffer[0] = protectStatus[0] & 0xFFFFU;
        optBuffer[1] = (protectStatus[0] >> 16U) & 0xFFFFU;
        optBuffer[2] = protectStatus[1] & 0xFFFFU;
        optBuffer[3] = (protectStatus[1] >> 16U) & 0xFFFFU;
        statusRes = EFLASH_OptionPageProgram(DFLASH_WRITE_PROTECT_BASE, optBuffer, DFLASH_WRITE_PROTECT_NUM);
        if (EFLASH_STATUS_SUCCESS != statusRes)
        {
            statusRes = EFLASH_STATUS_ERROR;
        }
    }
    else
    {
        statusRes = EFLASH_STATUS_ERROR;
    }

    return statusRes;
}

/*!
 * @brief Set P&D-Flash write protection by register.
 *
 * @param[in] sel: P&D-Flash select
              - 0: P-Flash
              - 1: D-Flash
 * @param[in] protectStatusLow: write protection status value for page 0~127
 * @param[in] protectStatusHigh: write protection status value for page 128~255
 * @return EFLASH STATUS: eflash operation status
 */
EFLASH_StatusType EFLASH_SetWriteProtectionByReg(uint8_t sel, uint32_t protectStatusLow, uint32_t protectStatusHigh)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;

    /* Write to protection register */
    if(!sel)
    {
        EFLASH_SetPWriteProRegHigh(protectStatusHigh);
        EFLASH_SetPWriteProRegLow(protectStatusLow);
        if((protectStatusLow != EFLASH_GetPWriteProRegLow()) || (protectStatusHigh != EFLASH_GetPWriteProRegHigh()))
        {
            statusRes = EFLASH_STATUS_ERROR;
        }
    }
    else
    {
        EFLASH_SetDWriteProRegHigh(protectStatusHigh);
        EFLASH_SetDWriteProRegLow(protectStatusLow);
        if((protectStatusLow != EFLASH_GetDWriteProRegLow()) || (protectStatusHigh != EFLASH_GetDWriteProRegHigh()))
        {
            statusRes = EFLASH_STATUS_ERROR;
        }
    }

    return statusRes;
}

/*!
 * @brief Set external reset enable or disable.
 *
 * @param[in] state: external reset status
 * @return EFLASH STATUS: eflash operation status
 */
EFLASH_StatusType EFLASH_SetExReset(ACTION_Type state)
{
    EFLASH_StatusType statusRes = EFLASH_STATUS_SUCCESS;
    uint32_t optBuffer = 0U;

    EFLASH_CLEAR_STAT_ERROR_BITS();
    statusRes = EFLASH_PageErase(EXTERN_RESET_CTRL_BASE);
    if (EFLASH_STATUS_SUCCESS == statusRes)
    {
        optBuffer = (ENABLE == state) ? 0xFU : 0x0U;
        statusRes = EFLASH_PageProgram(EXTERN_RESET_CTRL_BASE, &optBuffer, EXTERN_RESET_CTRL_NUM);
        if (EFLASH_STATUS_SUCCESS != statusRes)
        {
            statusRes = EFLASH_STATUS_ERROR;
        }
    }
    else
    {
        statusRes = EFLASH_STATUS_ERROR;
    }

    return statusRes;
}

/*!
 * @brief Enable ECC 2-bit error interrupt.
 *
 * @param[in] enable
 * @return none
 */
void EFLASH_SetECCInterrupt(ACTION_Type enable)
{
    /* Enable the double bit fault detect interrupt */
    EFLASH_SetECCIRQ(enable);
    NVIC_EnableIRQ(ECC_IRQn);
}

/*!
 * @brief Install ECC 2-bit error interrupt call back function.
 *
 * @param[in] callback: call back function pointer
 * @return none
 */
void EFLASH_InstallECCCallback(DeviceCallback_Type callback)
{
    DEVICE_ASSERT(NULL != callback);

    s_eccFlashCallback = callback;
}

/*!
 * @brief ECC_FLASH error interrupt ISR.
 *
 * @param[in] none
 * @return none
 */
void ECC_EFLASH_CommonISR(void)
{
   uint32_t wpara = 0U;

    /* store device status */
    wpara = EFLASH_GetECCIRQFlag();
    EFLASH_ClearECCIRQFlag();

    if (NULL != s_eccFlashCallback)
    {
        s_eccFlashCallback(EFLASH, wpara, 0U);
    }
}

/* =============================================  EOF  ============================================== */
